<script setup lang="ts">
import { getCheckApisList } from '@/api/api-manage/my-list'
import { commonExportListToExcel } from '@/api/common'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'

import { usePagination } from '@/hooks/usePagination'
import useTableRowSelection from '@/hooks/useTableRowSelection'
import useDictStore from '@/store/modules/dict'
import { ModalShowType } from '@/types/common'
import { formatDate, omitEmptyValue } from '@/utils/common'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
import { isNil } from 'lodash-es'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import approveModal from './approve-modal.vue'
import { useTableHeight } from '@/hooks/useTableHeight'

const dictStore = useDictStore()
const { api_check_status } = dictStore.getDicts('api_check_status')

defineOptions({
  name: 'api-manage/list',
})

const router = useRouter()
const loading = ref(false)
const queryParams = reactive({
  apiName: '',
  createByName: '',
  checkStatus: '',
})
const searchDateRange = ref<[string, string]>(['', ''])
const searchDateRangeParams = computed(() =>
  !isNil(searchDateRange.value)
    ? {
        'params[beginCreateTime]': searchDateRange.value[0],
        'params[endCreateTime]': searchDateRange.value[1],
      }
    : null
)
const { tableHeight, tableRef } = useTableHeight()
const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
  },
  {
    label: '接口ID',
    prop: 'id',
    minWidth: 100,
  },
  {
    label: '接口名称',
    prop: 'apiName',
    minWidth: 150,
  },
  {
    label: '创建人/单位',
    prop: 'createBy',
    minWidth: 150,
    formatter({ createBy, deptName }) {
      return `${createBy}/${deptName}`
    },
  },
  {
    label: '创建时间',
    prop: 'createTime',
    minWidth: 180,
    formatter: ({ createTime }) => formatDate(createTime),
  },
  {
    label: '接口状态',
    prop: 'checkStatus',
    minWidth: 100,
    formatter({ checkStatus }) {
      return api_check_status.getLabel(checkStatus)
    },
  },
  {
    label: '审核人',
    prop: 'checkBy',
    minWidth: 150,
  },
  {
    label: '操作时间',
    prop: 'checkTime',
    minWidth: 180,
    formatter: ({ checkTime }) => formatDate(checkTime),
  },
  {
    label: '操作',
    fixed: 'right',
    width: 180,
    slot: 'operation',
  },
]
const dataList = ref([])
/** 查询列表 */
async function onSearch() {
  loading.value = true
  const { rows, total } = await getCheckApisList(
    omitEmptyValue({
      apiName: queryParams.apiName,
      checkStatus: queryParams.checkStatus,
      ...searchDateRangeParams.value,
      createByName: queryParams.createByName,
      ...paginationParams.value,
    })
  )
  dataList.value = rows
  pagination.total = total

  setTimeout(() => {
    loading.value = false
  }, 500)
}

/** 重置新增的表单  */
async function resetForm() {
  queryParams.apiName = ''
  queryParams.createByName = ''
  queryParams.checkStatus = ''
  searchDateRange.value = ['', '']
  await onSearch()
}

const { selectedRows, onRowSelectionChange } = useTableRowSelection()

/** 导出按钮操作 */
function onExport() {
  const params = {
    // ...omitEmptyValue(queryParams),
    ids: selectedRows.value.map((item) => item.id),
  }
  commonExportListToExcel('/manage/apiInfo/checkExport', params)
}

onMounted(() => {
  onSearch()
})

const modalShow = ref(ModalShowType.Hide)
const termId = ref<number | null>(null)
</script>

<template>
  <div class="main table-view-layout">
    <el-form
      ref="formRef"
      :inline="true"
      :model="queryParams"
      class="bg-el-bg w-[99/100] pl-8 pt-4"
    >
      <el-form-item>
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入接口名称申请关键词"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.createByName"
          placeholder="请输入创建人/单位搜索"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="searchDateRange">
        <el-date-picker
          v-model="searchDateRange"
          unlink-panels
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.checkStatus"
          placeholder="接口状态"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in api_check_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch()"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm"> 重置 </el-button>
        <el-button @click="onExport">导出数据</el-button>
      </el-form-item>
    </el-form>
    <PureTableBar>
      <template #table>
        <pure-table
          ref="tableRef"
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :max-height="tableHeight"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }"
          @page-size-change="changePageSize"
          @page-current-change="changePageNumber"
          @selection-change="onRowSelectionChange"
        >
          <template #operation="{ row }">
            <el-button
              link
              class="reset-margin"
              type="primary"
              :disabled="api_check_status.getLabel(row.checkStatus) !== '待审核'"
              @click="
                () => {
                  modalShow = ModalShowType.Edit
                  termId = row.id
                }
              "
            >
              审批
            </el-button>
            <el-button
              link
              class="reset-margin"
              type="primary"
              @click="
                router.push({
                  path: '/api-manage/detail',
                  query: { id: row.id },
                })
              "
            >
              接口详情
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <approve-modal v-model:modal-show="modalShow" :term-id="termId" :on-search="onSearch" />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
